package cc.iits.demo.crane.web.support.interceptor;


import cc.iits.demo.crane.commom.IdCreater;
import cc.iits.demo.crane.web.support.Constants;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 会话拦截
 * @author 易俊
 */
public class SessionHandlerInterceptor implements HandlerInterceptor {

    private final static Logger logger = LoggerFactory.getLogger(SessionHandlerInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String sessionId = getSessionId(request);
        String token = getToken(request);
        // session
        if (StringUtils.isEmpty(sessionId)) {
            //设置新 sessionId
            sessionId = IdCreater.shortUuid();
            response.addCookie(new Cookie(Constants.SESSION_ID, sessionId));
        }
        request.setAttribute(Constants.SESSION_ID, sessionId);

        // token
        request.setAttribute(Constants.TOKEN, token == null ? StringUtils.EMPTY : token);
        return true;
    }

    private String getSessionId(HttpServletRequest request) {
        return getCookie(request,Constants.SESSION_ID);
    }

    private String getToken(HttpServletRequest request) {
        String temp = request.getHeader(Constants.TOKEN);
        return StringUtils.isNotEmpty(temp) ? temp : getCookie(request, Constants.TOKEN);
    }

    private String getCookie(HttpServletRequest request,String name) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equalsIgnoreCase(name)) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }
}
